package com.zxc.service.impl;

import com.zxc.controller.util.Convert;
import com.zxc.dao.*;
import com.zxc.model.*;
import com.zxc.service.OnlineExamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 试卷表(OnlineExam)表服务实现类
 *
 */
@Service
public class OnlineExamServiceImpl implements OnlineExamService {
    @Autowired
    private OnlineExamDao onlineExamDao;
    @Autowired
    private OnlineExamQuestionDao onlineExamQuestionDao;
    @Autowired
    OnlineExamStudentDao onlineExamStudentDao;
    @Autowired
    QuestionDao questionDao;
    @Autowired
    OnlineExamRecordDao onlineExamRecordDao;
//    @Autowired
//    SysUserDao sysUserDao;

    @Override
    public OnlineExam queryById(Integer OnlineExamId) {
        OnlineExam exam = this.onlineExamDao.queryById(OnlineExamId);
        if (exam == null) {
            return null;
        }
        //设置其日期的格式
        List<OnlineExamQuestion> examQuestions = onlineExamQuestionDao.selectOnlineExamQuestionListByExamId(OnlineExamId);
        if (examQuestions != null) {
            Integer ids[] = new Integer[examQuestions.size()];
            String idsStr = "";
            for (int i = 0; i < examQuestions.size(); i++) {
                ids[i] = examQuestions.get(i).getQuestionId();
                idsStr += examQuestions.get(i).getQuestionId() + ",";
            }
            exam.setIds(ids);
            exam.setIdsStr(idsStr);
            //查询出需要参加考试的学生的信息
            OnlineExamStudent examStudent = new OnlineExamStudent();
            examStudent.setExamId(OnlineExamId);
            List<OnlineExamStudent> examStudents = onlineExamStudentDao.queryAll(examStudent);
            Integer[] studentIds = new Integer[examStudents.size()];
            for (int i = 0; i < examStudents.size(); i++) {
                studentIds[i] = examStudents.get(i).getStudentId();
            }
            exam.setStudentIds(studentIds);
        }
        return exam;
    }

    /**
     * 新增数据
     *
     * @param exam 实例对象
     * @return 实例对象
     */
    @Override
    @Transactional
    public int insert(OnlineExam exam) {
        int insert = this.onlineExamDao.insert(exam);
        return insert;
    }

    /**
     * 修改数据
     *
     * @param exam 实例对象
     * @return 实例对象
     */
    @Override
    @Transactional
    public int update(OnlineExam exam) {
        //删除关联
        Integer[] ids = exam.getIds();
        //删除关联，根据examid
        onlineExamQuestionDao.deleteByExamId(exam.getExamId());
        //删除和学生的关联
        onlineExamStudentDao.deleteByExamId(exam.getExamId());
        double score = 0;
        //重新设置关联
        if (ids != null) {
            for (Integer id : ids) {
                OnlineExamQuestion examQuestion = new OnlineExamQuestion();
                examQuestion.setExamId(exam.getExamId());
                examQuestion.setQuestionId(id);
                onlineExamQuestionDao.insert(examQuestion);
                score += questionDao.queryById(id).getScore();
            }
        }
        exam.setScore(score);
        //重置和学生的关联
        if (exam.getStudentIds() != null) {
            for (Integer studentId : exam.getStudentIds()) {
                OnlineExamStudent examStudent = new OnlineExamStudent();
                examStudent.setExamId(exam.getExamId());
                examStudent.setStudentId(studentId);
                onlineExamStudentDao.insert(examStudent);
            }
        }
        return this.onlineExamDao.update(exam);
    }

    @Override
    public int updateScore(OnlineExam exam) {
        return this.onlineExamDao.updateScore(exam);
    }


    /**
     * 通过主键删除数据
     *
     * @param examId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer examId) {
        return this.onlineExamDao.deleteById(examId) > 0;
    }

    @Override
    @Transactional
    public int deleteByIds(String ids) {
        Integer[] examIds = Convert.toIntArray(ids);
        return onlineExamDao.deleteByIds(examIds);
    }

    @Override
    public List<OnlineExam> findOnlineExamList(OnlineExam exam) {
        return onlineExamDao.queryAll(exam);
    }

    @Override
    public StudentExamDetail getOnlineExamForStudentByOnlineExamId(Integer examId, Integer userId) {

        List<OnlineExamQuestion> examQuestions = onlineExamQuestionDao.selectOnlineExamQuestionListByExamId(examId);

        OnlineExam exam = onlineExamDao.queryById(examId);
        //新建5中类型的List集合
        List<Question> radioQuestion = new ArrayList<>();
        List<Question> checkboxQuestion = new ArrayList<>();
        List<Question> blackQuestion = new ArrayList<>();
        List<Question> judgeQuestion = new ArrayList<>();
        List<Question> shortQuestion = new ArrayList<>();

        StudentExamDetail studentExamDetail = new StudentExamDetail();

        //设置试卷信息
        studentExamDetail.setExamName(exam.getExamName());
        studentExamDetail.setLastTime(exam.getExamLastTime());
        studentExamDetail.setStartDate(exam.getExamStartDate());
        studentExamDetail.setExamId(examId);

        //试卷分数
        double score = 0;
        for (OnlineExamQuestion examQuestion : examQuestions) {
            Question question = questionDao.queryById(examQuestion.getQuestionId());
            //查询出已经保存的有的数据，方便页面回显
            OnlineExamRecord examRecord = onlineExamRecordDao.selectRecordByExamIdAndQuestionIdAndStuId(examId, question.getId(), userId);
            String answer = "";
            if (examRecord == null) {
                question.setFinalScore(0D);
            } else {
                question.setFinalScore(examRecord.getFinalScore());
                answer = examRecord.getAnswer();
            }
            score += question.getScore();

            setAnswer(answer, question);

            if ("1".equals(question.getType())) {
                //获取单选
                radioQuestion.add(question);
            } else if ("2".equals(question.getType())) {
                //获取多选
                checkboxQuestion.add(question);
            } else if ("3".equals(question.getType())) {
                //获取填空
                blackQuestion.add(question);
            } else if ("4".equals(question.getType())) {
                //获取判断
                judgeQuestion.add(question);
            } else if ("5".equals(question.getType())) {
                //获取简答
                shortQuestion.add(question);
            }
        }

        studentExamDetail.setCheckboxQuestion(checkboxQuestion);
        studentExamDetail.setRadioQuestion(radioQuestion);
        studentExamDetail.setShortQuestion(shortQuestion);
        studentExamDetail.setJudgeQuestion(judgeQuestion);
        studentExamDetail.setBalckQuestion(blackQuestion);

        studentExamDetail.setScore(score);

        return studentExamDetail;
    }

    @Override
    public List<OnlineExam> findOnlineExamListForStu(OnlineExam exam, Integer id) {
        List<OnlineExam> examList = findOnlineExamList(exam);
        List<OnlineExam> returnExams = new ArrayList<>();
        for (OnlineExam temp : examList) {
            OnlineExamStudent examStudent = onlineExamStudentDao.selectByExamIdAndStuId(temp.getExamId(), id);
            //说明没有指定该学生可以考试
            if (examStudent == null) {
                //删除此条记录
                continue;
            } else if ("0".equals(examStudent.getStatus())) {
                //说明还没有做，可以做
                temp.setAccessed(false);
            } else if ("1".equals(examStudent.getStatus())) {
                //说明已经做过了，只能显示不能做
                temp.setAccessed(true);
            }
            temp.setTotalScore(examStudent.getTotalScore());
            returnExams.add(temp);
        }
        return returnExams;
    }

    @Override
    public List<OnlineExam> findOnlineExamListToReview(OnlineExam exam) {
        List<OnlineExam> examList = findOnlineExamList(exam);
        List<OnlineExam> examsReturn = new ArrayList<>();
        for (OnlineExam temp : examList) {
            Integer examId = temp.getExamId();
            List<OnlineExamStudent> examStudents = onlineExamStudentDao.selectByExamId(examId);
            for (OnlineExamStudent examStudent : examStudents) {
                //过滤掉还未参加考试的学生
                if ("0".equals(examStudent.getStatus())) {
                    continue;
                }
                OnlineExam returnExam = new OnlineExam();
                returnExam.setExamId(examId);
                returnExam.setReviewerId(temp.getReviewerId());
                returnExam.setStudentId(examStudent.getStudentId());
                returnExam.setExamName(temp.getExamName());

//                returnExam.setStudentName(sysUserDao.selectUserById(examStudent.getStudentId()).getLoginName());
                returnExam.setStudentName("testStudentName");
                returnExam.setReading(examStudent.getReading());
                returnExam.setExamStartDate(temp.getExamStartDate());
                returnExam.setSubname(temp.getSubname());
                examsReturn.add(returnExam);
            }
        }
        return examsReturn;
    }

    @Override
    public StudentExamDetail findOnlineExamDetailToReview(Integer examId, Integer stuId) {

        List<OnlineExamQuestion> examQuestions = onlineExamQuestionDao.selectOnlineExamQuestionListByExamId(examId);
        OnlineExam exam = onlineExamDao.queryById(examId);
        List<Question> radioQuestion = new ArrayList<>();
        List<Question> checkboxQuestion = new ArrayList<>();
        List<Question> blackQuestion = new ArrayList<>();
        List<Question> judgeQuestion = new ArrayList<>();
        List<Question> shortQuestion = new ArrayList<>();

        StudentExamDetail studentExamDetail = new StudentExamDetail();
        studentExamDetail.setExamName(exam.getExamName());
        studentExamDetail.setLastTime(exam.getExamLastTime());
        studentExamDetail.setStartDate(exam.getExamStartDate());
        studentExamDetail.setExamId(examId);


        //获取学生总成绩
        OnlineExamStudent examStudent = onlineExamStudentDao.selectByExamIdAndStuId(examId, stuId);
        //设置学生总成绩
        studentExamDetail.setTotalScore(examStudent.getTotalScore());

        double score = 0;

        for (OnlineExamQuestion examQuestion : examQuestions) {
            Question question = questionDao.queryById(examQuestion.getQuestionId());
            //查询出已经保存的有的数据，方便页面回显
            OnlineExamRecord examRecord = onlineExamRecordDao.selectRecordByExamIdAndQuestionIdAndStuId(examId, question.getId(), stuId);
            String answer = "";
            if (examRecord == null) {
                continue;
            }
            question.setFinalScore(examRecord.getFinalScore());
            answer = examRecord.getAnswer();

            setAnswer(answer, question);

            score += question.getScore();
            if ("1".equals(question.getType())) {
                //获取单选
                radioQuestion.add(question);
            } else if ("2".equals(question.getType())) {
                //获取单选
                checkboxQuestion.add(question);
            } else if ("3".equals(question.getType())) {
                //获取填空
                blackQuestion.add(question);
            } else if ("4".equals(question.getType())) {
                //获取判断
                judgeQuestion.add(question);
            } else if ("5".equals(question.getType())) {
                //获取简答
                shortQuestion.add(question);
            }
        }

        studentExamDetail.setCheckboxQuestion(checkboxQuestion);
        studentExamDetail.setRadioQuestion(radioQuestion);
        studentExamDetail.setShortQuestion(shortQuestion);
        studentExamDetail.setJudgeQuestion(judgeQuestion);
        studentExamDetail.setBalckQuestion(blackQuestion);

        studentExamDetail.setScore(score);
        return studentExamDetail;
    }

    @Override
    public List<Map> querySubject() {
        return onlineExamDao.querySubject();
    }

    /**
     * 设置答案
     *
     * @param answer
     * @param question
     */
    private void setAnswer(String answer, Question question) {
        //单选 多选ABC
        switch (question.getType()) {
            case "1":
            case "2":
                String[] split = answer.split(",");
                for (String s : split) {
                    if ("A".equals(s)) {
                        question.setOptionACheckedStu("A");
                    } else if ("B".equals(s)) {
                        question.setOptionBCheckedStu("B");
                    } else if ("C".equals(s)) {
                        question.setOptionCCheckedStu("C");
                    } else if ("D".equals(s)) {
                        question.setOptionDCheckedStu("D");
                    }
                }
                break;
            //判断
            case "4":
                if ("1".equals(answer)) {
                    question.setJudgeAnswer1Stu("1");
                } else if ("0".equals(answer)) {
                    question.setJudgeAnswer0Stu("0");
                }
                break;
            case "3":
            case "5":
                question.setTextAnswerStu(answer);
                break;
            default:
                break;
        }
    }

}